// pages/myExam/myExam.js
const http = require('../../utils/http.js');

Page({
  data: {
    exams: [
      {
        name: "专升本考试",
        time: "2025-04-01",
        description: "点击查看专升本考试报名信息",
        page: "/pages/zhuanshengben/zsb_exam_registrationInfo/zsb_exam_registrationInfo",
        available: false
      },
      {
        name: "成人高考",
        time: "2025-04-05",
        description: "点击查看成人高考报名信息",
        page: "/pages/chengkao/ck_exam_registrationInfo/ck_exam_registrationInfo",
        available: false
      },
      {
        name: "中考",
        time: "2024-06-15 09:00",
        description: "点击查看初中学业水平考试报名信息",
        page: "/pages/zhongkao/zk_exam_registrationInfo/zk_exam_registrationInfo",
        available: false
      },
      {
        name: "高考",
        time: "2024-06-07 09:00",
        description: "点击查看普通高等学校招生全国统一考试报名信息",
        page: "/pages/gaokao/gk_exam_registrationInfo/gk_exam_registrationInfo",
        available: false
      },
      {
        name: "自考",
        time: "2024-06-07 09:00",
        description: "点击查看高等教育自学考试报名信息",
        page: "/pages/zikao/zk_exam_registrationInfo/zk_exam_registrationInfo",
        available: false
      },
    ],
  },

  async onLoad() {
    try {
      // 从本地缓存获取考生身份证号（之前在 profile.js 已保存）
      const baseInfo = wx.getStorageSync('base_candidate_info');
      if (!baseInfo || !baseInfo.id_number) {
        wx.showToast({
          title: "未找到考生信息，请重新登录",
          icon: "none",
        });
        return;
      }

      const idNumber = baseInfo.id_number;
      const url = `/baoming/candidate/examInfo/${idNumber}`;

      // 🔹 调用后端接口验证报名情况
      const res = await http.get(url);
      if (!res || res.statusCode !== 200) {
        wx.showToast({ title: "获取报名信息失败", icon: "error" });
        return;
      }

      const data = res.data.data || {};

      // 🔹 根据接口数据设置各考试是否报名 (存在则 available=true)
      this.setData({
        "exams[0].available": !!data.zsb_exam,       // 专升本
        "exams[1].available": !!data.ck_exam,        // 成考
        "exams[2].available": !!data.zk_exam,  // 中考
        "exams[3].available": !!data.gk_exam,        // 高考
        "exams[4].available": !!data.zikao_exam,     // 自考
      });

      console.log("报名状态更新完成：", this.data.exams);
    } catch (err) {
      console.error("获取报名信息出错：", err);
      wx.showToast({
        title: "系统错误，请稍后重试",
        icon: "none",
      });
    }
  },

  // 🔹 跳转逻辑：仅在 available=true 时允许跳转
  goToExamPage(e) {
    const index = e.currentTarget.dataset.index;
    const exam = this.data.exams[index];

    if (exam && exam.available) {
      wx.navigateTo({
        url: exam.page,
        success: () => console.log("✅ 跳转成功：", exam.page),
        fail: err => console.error("❌ 跳转失败：", err)
      });
    } else {
      wx.showToast({
        title: "未报名该考试，无法跳转",
        icon: "none",
        duration: 2000
      });
    }
  }
});